package com.hudilao.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hudilao.common.BaseContext;
import com.hudilao.common.R;
import com.hudilao.dto.*;
import com.hudilao.entity.CustomerMembership;
import com.hudilao.entity.Order;
import com.hudilao.entity.OrderDetail;
import com.hudilao.exception.OrderException;
import com.hudilao.service.CartService;
import com.hudilao.service.CustomerMembershipService;
import com.hudilao.service.OrderService;
import com.hudilao.vo.OrderBalancePaymentVO;
import com.hudilao.vo.OrderHistoryVO;
import com.hudilao.vo.OrderSubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CustomerMembershipService customerMembershipService;

    @Autowired
    private CartService cartService;

    /**
     * 用户下单
     * @param orderSubmitDTO
     * @return
     */
    @PostMapping("/submit")
    @Transactional
    public R<OrderSubmitVO> submit(@RequestBody OrderSubmitDTO orderSubmitDTO){

        log.info("订单数据：{}",orderSubmitDTO);
        long customerId = BaseContext.getCurrentId();

        try{
            //加入购物车
            cartService.add(orderSubmitDTO.getCartAddDTO(),customerId);

            //提交订单，将购物车中的数据添加到订单和订单详情中，生成订单
            OrderSubmitVO orderSubmitVO = orderService.submit(orderSubmitDTO, customerId);

            //清空购物车
            cartService.remove(customerId);

            return R.success(orderSubmitVO);
        }catch(OrderException e){
            cartService.remove(customerId);

            log.error("订单提交失败：{}",e.getMessage(),e);
            return R.error("订单提交失败");
        }

    }

    /**
     * 用户支付
     * @param orderPaymentDTO
     * @return
     * @throws Exception
     */
    @PutMapping("/payment")
    public R<OrderBalancePaymentVO> payment(@RequestBody OrderPaymentDTO orderPaymentDTO) throws Exception{

        //微信支付
//        OrderPaymentVO orderPaymentVO = orderService.pay(orderPaymentDTO);

        //支付
        return orderService.payByBalance(orderPaymentDTO);

    }

    /**
     * 用户查看历史订单
     * @return
     */
    @GetMapping("/history")
    public R<List<OrderHistoryVO>> historyOrders(){

        //获取当前用户
        long customerId = BaseContext.getCurrentId();

        List<OrderHistoryVO> orderHistoryDTOS = orderService.getOrdersById(customerId);
        if (orderHistoryDTOS != null && !orderHistoryDTOS.isEmpty()) {
            return R.success(orderHistoryDTOS);
        } else {
            return R.error("没有找到历史订单");
        }
    }

    /**
     *
     */




    //管理端
    /**
     * 管理端：订单分页查询
     * @param page
     * @param pageSize
     * @param username
     */
    // 订单分页查询接口
    @GetMapping("/page")
    public R<Page<OrderDTO>> getOrdersByUsername(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String username) {

        //构建分页查询page
        Page<OrderDTO> ordersPage = orderService.getOrdersByUsername(page, pageSize, username);

        log.info(username);
        //返回分页查询page
        return R.success(ordersPage);
    }

    /**
     * 管理端：订单分页查询-已提交
     * @param page
     * @param pageSize
     */
    @GetMapping("/status/submitted")
    public R<Page<OrderDTO>> getSubmittedOrders(
            @RequestParam int page,
            @RequestParam int pageSize) {

        //构建分页查询page
        Page<OrderDTO> ordersPage = orderService.getOrdersByStatus(page, pageSize, Order.SUBMITTED);

        //返回已提交分页查询page
        return R.success(ordersPage);
    }


    /**
     * 管理端：订单分页查询-已支付
     * @param page
     * @param pageSize
     */
    @GetMapping("/status/paid")
    public R<Page<OrderDTO>> getPaidOrders(
            @RequestParam int page,
            @RequestParam int pageSize) {

        //构建分页查询page
        Page<OrderDTO> ordersPage = orderService.getOrdersByStatus(page, pageSize, Order.PAID);

        //返回已支付分页查询page
        return R.success(ordersPage);
    }


    /**
     * 管理端：订单分页查询-已完成
     * @param page
     * @param pageSize
     */
    @GetMapping("/status/finished")
    public R<Page<OrderDTO>> getFinishedOrders(
            @RequestParam int page,
            @RequestParam int pageSize) {

        //构建分页查询page
        Page<OrderDTO> ordersPage = orderService.getOrdersByStatus(page, pageSize, Order.FINISHED);

        //返回已完成分页查询page
        return R.success(ordersPage);
    }


    /**
     * 管理端：订单分页查询-已评价
     * @param page
     * @param pageSize
     */
    @GetMapping("/status/reviewed")
    public R<Page<OrderDTO>> getReviewedOrders(
            @RequestParam int page,
            @RequestParam int pageSize) {

        //构建分页查询page
        Page<OrderDTO> ordersPage = orderService.getOrdersByStatus(page, pageSize, Order.REVIEWED);

        log.info("---order.reviewed---");
        log.info(Order.REVIEWED.toString());
        //返回已评价分页查询page
        return R.success(ordersPage);
    }

    /**
     * 管理端：获取各类订单数量以及总订单数量
     * @return int[] 依次返回已提交、已支付、已完成、已评价订单的数量以及总订单数量
     */
    @GetMapping("/count/status")
    public int[] getOrderStatusCount() {
        return orderService.getOrderStatusCount();
    }


    /**
     * 管理端：更新订单状态为2已查询
     * @param order
     */
//    @PutMapping("/deliver/{orderId}")
//    public R<String> deliverOrder(@PathVariable Long orderId) {
//
//        //根据订单id更新订单状态为已完成
//        ///String result = orderService.updateOrderStatus(orderId, Order.FINISHED);
//        R<String> result = orderService.updateOrderStatus(orderId,Order.FINISHED);
//        // 返回更新结果
//        return result;
//    }

    @PutMapping("/deliver")
    public R<String> deliverOrder(@RequestBody Order order) {

        //根据订单id更新订单状态为已完成
        ///String result = orderService.updateOrderStatus(orderId, Order.FINISHED);
        //R<String> result = orderService.updateOrderStatus(orderId,Order.FINISHED);
        // 返回更新结果
        return orderService.updateOrderStatus(order);
    }


    /**
     * 管理端：通过id查看订单详情
     * @param id
     */
    @GetMapping("/detail/{id}")
    public R<OrderDetailDTO> getOrderDetails(@PathVariable Long id) {

        //获取订单详情
        OrderDetailDTO orderDetailDTO = orderService.getOrderDetails(id);

        //获取详情结果
        if (orderDetailDTO != null) {
            return R.success(orderDetailDTO);
        } else {
            return R.error("订单详情获取失败");
        }
    }

}
